package com.szh.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szh.eduservice.entity.EduCourse;
import com.szh.eduservice.entity.EduCourseDescription;
import com.szh.eduservice.entity.frontvo.CourseFrontVo;
import com.szh.eduservice.entity.frontvo.CourseWebVo;
import com.szh.eduservice.entity.vo.CourseInfoVo;
import com.szh.eduservice.entity.vo.CoursePublishVo;
import com.szh.eduservice.entity.vo.CourseQuery;
import com.szh.eduservice.mapper.EduCourseMapper;
import com.szh.eduservice.service.EduChapterService;
import com.szh.eduservice.service.EduCourseDescriptionService;
import com.szh.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.eduservice.service.EduVideoService;
import com.szh.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-09-04
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService courseDescriptionService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private EduVideoService videoService;

    //添加课程基本信息
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //向edu_course课程表中添加课程基本信息
        //将courseInfoVo对象转换为eduCourse对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert <= 0) {
            throw new GuliException(20001,"添加课程基本信息失败");
        }

        //获取添加之后的课程id
        String cid = eduCourse.getId();

        //向edu_course_description课程简介表中添加课程简介信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        //手动设置课程简介信息的id值，该值就是对应课程基本信息中的id值
        courseDescription.setId(cid);
        //手动设置课程简介信息的描述
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.save(courseDescription);

        return cid;
    }

    //根据课程id查询课程基本信息
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        //查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);

        //查询课程简介表
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    //修改课程信息
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //修改课程表中的信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if (update == 0) {
            throw new GuliException(20001,"修改课程信息失败");
        }

        //修改课程简介表中的信息
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.updateById(description);
    }

    //根据课程id查询课程的特定信息
    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    //删除课程
    @Override
    public void removeCourse(String courseId) {
        //根据课程id删除课程中的小节
        videoService.removeVideoByCourseId(courseId);

        //根据课程id删除课程中的章节
        chapterService.removeChapterByCourseId(courseId);

        //根据课程id删除课程中的描述简介
        courseDescriptionService.removeById(courseId);

        //根据课程id删除课程本身
        int result = baseMapper.deleteById(courseId);
        if (result == 0) {
            throw new GuliException(20001,"删除课程失败");
        }
    }

    //分页查询课程
    @Override
    public Map pageListCourse(long current, long limit) {
        Page<EduCourse> page = new Page<>(current,limit);
        baseMapper.selectPage(page,null);

        long total = page.getTotal(); //总记录数
        List<EduCourse> records = page.getRecords();

        Map map = new HashMap();
        map.put("total",total);
        map.put("rows",records);

        return map;
    }

    //条件查询（带分页）
    @Override
    public Map pageCourseCondition(long current, long limit, CourseQuery courseQuery) {
        //创建page对象
        Page<EduCourse> pageCourse = new Page<>(current,limit);

        //构建查询条件对象
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();
        String begin = courseQuery.getBegin();
        String end = courseQuery.getEnd();

        //动态sql语句的拼接
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title",title);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if (!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create",begin);
        }
        if (!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create",end);
        }
        wrapper.orderByDesc("gmt_create");

        //调用方法实现条件查询分页显示
        baseMapper.selectPage(pageCourse,wrapper);

        //将总记录数、数据集封装到map集合中返回
        long total = pageCourse.getTotal(); //总记录数
        List<EduCourse> records = pageCourse.getRecords(); //所有数据集
        Map map = new HashMap();
        map.put("total",total);
        map.put("rows",records);
        return map;
    }

    //查询前8条热门课程
    @Override
    @Cacheable(key = "'selectCourse'",value = "course")
    public List<EduCourse> getCourseList() {
        QueryWrapper<EduCourse> wrapperCourse = new QueryWrapper<>();
        wrapperCourse.orderByDesc("view_count");
        wrapperCourse.last("limit 8");
        List<EduCourse> eduList = baseMapper.selectList(wrapperCourse);
        return eduList;
    }

    //条件查询带分页查询课程
    @Override
    public Map<String, Object> getFrontCourseList(Page<EduCourse> pageCourse, CourseFrontVo courseFrontVo) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空将其拼接到sql语句中
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) { //最新时间
            wrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) { //价格
            wrapper.orderByDesc("price");
        }
        //进行分页查询
        baseMapper.selectPage(pageCourse,wrapper);

        //获取分页相关的所有数据
        List<EduCourse> records = pageCourse.getRecords(); //分页数据集合
        long current = pageCourse.getCurrent(); //当前页
        long size = pageCourse.getSize(); //每页记录数
        long total = pageCourse.getTotal(); //总记录数
        long pages = pageCourse.getPages(); //总页数
        boolean hasPrevious = pageCourse.hasPrevious(); //是否有上一页
        boolean hasNext = pageCourse.hasNext(); //是否有下一页

        //把分页数据放到map集合
        Map<String,Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    //根据课程id，编写sql语句查询课程信息
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

}
